package com.class05.listener;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.*;
import java.text.SimpleDateFormat;
import java.util.logging.SimpleFormatter;
// 配置监听器，监听servletB
@WebListener("/servletB")
public class MySessionListener implements HttpSessionListener,
        HttpSessionAttributeListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {
//        1、获取session对象
        HttpSession session = se.getSession();
        System.out.println("session创建了，id为："+session.getId());
        System.out.println("session创建了，最大存活时间为：" +
                +session.getMaxInactiveInterval());
        System.out.println("session创建了");

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("session销毁了");
    }


    public void attributeAdded(HttpSessionBindingEvent event) {
        System.out.println("添加了属性名为：" + event.getName());

        System.out.println("添加了属性值为：" + event.getValue());
    }

    public void attributeRemoved(HttpSessionBindingEvent event) {
        System.out.println("删除了属性名为：" + event.getName());
        System.out.println("删除了属性值为：" + event.getValue());
    }

    public void attributeReplaced(HttpSessionBindingEvent event) {
        HttpSession session = event.getSession();
        String id = session.getId();
        System.out.println("session的id为：" + id);
        long creationTime = session.getCreationTime();
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(creationTime);
        System.out.println("session创建时间为：" + format);

        System.out.println("替换了属性名为：" + event.getName());
        System.out.println("替换了属性旧值为：" + event.getValue());
        Object name = session.getAttribute("name");
        System.out.println("替换之后的新值为：" + name);

    }
}
